package utils

import (
	"encoding/json"
	"fmt"
	"gocolly/model"
	"strconv"
	"strings"
	"time"
)

type MajorNewResponse struct {
	Code    string       `json:"code"`
	Message string       `json:"message"`
	Data    MajorNewData `json:"data"`
}

type MajorNewData struct {
	Item []model.MajorNew
}

func DedcodeMajorNewAndSave(jsonStr string) {
	var response MajorNewResponse
	decoder := json.NewDecoder(strings.NewReader(jsonStr))
	err := decoder.Decode(&response)
	if err != nil {
		panic("解析json错误：" + err.Error())
	}

	for _, majorNew := range response.Data.Item {
		model.UpdateOrCreateMajorNew(majorNew)
	}

}

func DecMajorNew() {
	headers := map[string]string{
		"Accept": "application/json, text/plain, */*",
		//"Accept-Encoding":    "gzip, deflate, br, zstd",
		"Accept-Language":    "zh-CN,zh;q=0.9",
		"Content-Length":     "202",
		"Content-Type":       "application/json",
		"Origin":             "https://www.gaokao.cn",
		"Priority":           "u=1, i",
		"Referer":            "https://www.gaokao.cn/",
		"Sec-Ch-Ua":          `Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"`,
		"Sec-Ch-Ua-Mobile":   `?0`,
		"Sec-Ch-Ua-Platform": "Windows",
		"Sec-Fetch-Dest":     "empty",
		"Sec-Fetch-Mode":     "cors",
		"Sec-Fetch-Site":     "cross-site",
		"User-Agent":         "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
	}

	for i := 1; i < 26; i++ {
		req := &Request{
			URL:     `https://api.zjzw.cn/web/api/?keyword=&level1=2&level2=&level3=&page=` + strconv.Itoa(i) + `&size=30&sort=&uri=apidata/api/gkv3/special/lists&signsafe=0a1e8d4b993deb02a00ec408770e7d68`,
			Headers: headers,
		}
		res := req.Do()

		DedcodeMajorNewAndSave(string(res))
		fmt.Println("完成..............第" + strconv.Itoa(i) + "页")
		time.Sleep(time.Second * 20)

	}
}
